Skip to content

Decorating an IEnumerable request property with JsonRequired causes instantiation of abstract ICollection #5140

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
jonmarozick opened this issue Apr 10, 2025 · 0 comments

Comments

@jonmarozick
Copy link

Describe the bug

A request class with an IEnumerable property decorated with JsonRequired is assigned a new ICollection which generates a compiler error.

Version of NSwag toolchain, computer and .NET runtime used

Both 14.2.0 and 14.3.0 have this issue. I didn't test prior versions.
C# .NET 8 WebAPI
Windows 10
Visual Studio Version 17.13.6

To Reproduce

public class SaveRequest
{
    [Newtonsoft.Json.JsonRequired]
    public IEnumerable<UserType> UserTypes { get; set; }
}

Generates this:

[System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.3.0.0 (NJsonSchema v11.2.0.0 (Newtonsoft.Json v13.0.0.0))")]
public partial class SaveRequest
{
    [Newtonsoft.Json.JsonProperty("userTypes", Required = Newtonsoft.Json.Required.Always, ItemConverterType = typeof(Newtonsoft.Json.Converters.StringEnumConverter))]
    public System.Collections.Generic.ICollection<UserType> UserTypes { get; set; } = new System.Collections.Generic.ICollection<UserType>();
}

Expected behavior

I would expect the generated code to be a concrete class such as a List.

[System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.3.0.0 (NJsonSchema v11.2.0.0 (Newtonsoft.Json v13.0.0.0))")]
public partial class SaveRequest
{
    [Newtonsoft.Json.JsonProperty("userTypes", Required = Newtonsoft.Json.Required.Always, ItemConverterType = typeof(Newtonsoft.Json.Converters.StringEnumConverter))]
    public System.Collections.Generic.ICollection<UserType> UserTypes { get; set; } = new System.Collections.Generic.List<UserType>();
}

Additional context

As a work around I removed the JsonRequired attribute and used a validator to ensure the incoming data has at least 1 item in the collection.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant